<template>
  <div class="zplayer">
    <audio :src='current.url' controls autoplay ref='audio' hidden></audio>
    <div class='audio'>
      <div class='music-pic'>
        <img :src='current.pic' v-if='current.pic'>
        <img src='../assets/def.jpg' v-if='!current.pic'>
        <div class='iconfont-box' :class="{on : isPaused}">
          <i class="iconfont" :class="isPaused ? 'icon-bofangqi3' : 'icon-zanting'" @click='play'></i>
        </div>
      </div>
      <div class='music-controls-box'>
        <div class='music-info'>
          {{current.title}} - {{current.author}}
        </div>
        <div class='music-lrc'>
          <div class='music-lrc-box' :style="{top:lrcNumber + 'px'}">
            <dl v-for='lrc in songLrc'>{{lrc | regularLrc}}</dl>
          </div>
        </div>
        <div class='music-controls'>
          <div class='song-bar-l'>
            <div class='song-btns'>
              <i class='iconfont icon-shangyishou' title='上一首' @click='preSong'></i>
              <i class='iconfont icon-xiayishou' title='下一首' @click='nextSong'></i>
            </div>
            <div class='song-volume'>
              <i class='iconfont icon-yinliang' title='音量' @click='isVolumeControls = !isVolumeControls'></i>
              <input type="range" name="points" min="1" max="10" class='volume-controls' ref='range' v-show='isVolumeControls'/>
            </div>
            <div class='song-loop'>
              <i class='iconfont' @click='loopIcon' :title='loopString' :class="classObject"></i>
            </div>
            <div class='song-menu'>
              <i class='iconfont icon-yinpingedan' title='播放列表' @click='playlistShow'></i>
            </div>
          </div>
          <div class='song-bar-r'>
            <div class='time-bar' ref='timeBar'>
              <div class='time-loaded'></div>
              <div class='time-played' :style="{width:currentTime + '%'}"><span class='time-thumb' ref='timeThumb'></span></div>
            </div>
          </div>
          <div class='time-number'>{{currentTimeSong | timer}} / {{time | timer}}</div>
        </div>
      </div>
      <!--最近播放列表-->
      <div class='playlist' v-show='isPlaylistShow'>
        <h3 @click='delALlSongs'>清空列表</h3>
        <ul>
          <li v-for='(song, index) in songList' :class="currentIndex === index ? 'on' : 'default'" >
            <dl class='' @click='playListClick(song, index)' >{{song.title}} - {{song.author}}</dl>
            <span class='playlistDel' @click='playlistDel(song, index)' title='删除'>X</span>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
  import Vue from 'vue'
  // 时间换算过滤器
  Vue.filter('timer', function (value) {
    value = Math.floor(value)
    let minute, second
    minute = Math.floor(value / 60) < 10 ? '0' + Math.floor(value / 60) : Math.floor(value / 60)
    second = value % 60 < 10 ? '0' + value % 60 : value % 60
    return minute + ':' + second
  })
  // 歌词正则写入页面
  Vue.filter('regularLrc', function (value) {
    return value.replace(/\[.*?\]/, '')
  })
  export default {
    data () {
      return {
        classObject: {
          'icon-danquxunhuan': true,
          'icon-xunhuan': false,
          'icon-suijibofang': false,
          'icon-shunxubofang': false
        },
        loopString: '单曲循环',
        currentIndex: 0, // 当前播放位置
        isPlaylistShow: false, // 播放列表
        time: 0, // 歌曲时长
        currentTimeSong: 0, // 绝对当前播放时间
        currentTime: 0, // 播放进度，这个是按照%算的
        stop: null, // 控制进度条是否前进
        isPaused: true, // 是否暂停
        songLrc: [], // 歌词
        songLrcTime: [], // 歌词时间数组
        lrcNumber: 0, // 歌词显示第几个
        current: [], // 当前歌曲对象
        loopTypeNumber: 1, // 循环模式判断 1 单曲 2 列表循环 3 随机播放 4 顺序播放
        isVolumeControls: false // 是否打开音量控件
      }
    },
    props: ['songList', 'volume'],
    watch: {
      songList () {
        // console.log('歌曲变化')
        this.init(true)
      },
      currentTime () {
        this.isPaused = this.$refs.audio.paused
      },
      currentTimeSong () { // 监视当前时间变化，改变歌词
        for (let i in this.songLrcTime) {
          // console.log(i + ':' + this.songLrcTime[i] + ':' + Math.floor(this.currentTimeSong))
          if (this.songLrcTime[i] === Math.floor(this.currentTimeSong)) {
            this.lrcNumber = -(i - 1) * 20
          }
        }
      }
    },
    mounted () {
      this.$nextTick(function () {
        // console.log('初始化')
        this.init(false)
      })
    },
    methods: {
      delALlSongs () {
        console.log('正在清空列表..')
        this.$emit('childrenSongRemoved')
      },
      init (isPlaying) {
        let _this = this
        console.log('播放器初始化中，this.songList的值是：', this.songList.length)
        if (this.songList.length === 0) {
          console.log('歌单中无歌曲，去找一找吧')
          return
        }
        this.setSong()
        clearInterval(_this.stop)
        // 播放已加载事件
        this.$refs.audio.addEventListener('canplaythrough', function (e) {
          _this.currentTime = 0
          // if (isPlaying) {
          //   _this.$refs.audio.play()
          // }
          _this.setPlayer()
        }, false)
        // 播放完成事件
        this.$refs.audio.addEventListener('ended', function (e) {
          console.log('播放完了' + _this.$refs.audio.currentTime)
          this.currentTime = 0
          _this.isPaused = false
          clearInterval(_this.stop)
          _this.loopType() // 循环开启
        }, false)
        this.$refs.audio.addEventListener('playing', function (e) {
          // console.log('playing')
        })
        this.$refs.audio.addEventListener('pause', function (e) {
          // console.log('pause')
        })
      },
      setPlayer () {
        // 时长获取
        let _this = this
        let audio = this.$refs.audio
        let timeThumbIsDown = false
        this.time = audio.duration
        // 音量获取
        audio.volume = this.volume / 10
        this.$refs.range.value = this.volume
        this.$refs.range.addEventListener('input', function (e) {
          // 修改音量
          audio.volume = _this.$refs.range.valueAsNumber / 10
          localStorage.setItem('volume', _this.$refs.range.valueAsNumber)
          // 告诉父组件，音乐变了
          _this.$emit('volumeChanged', _this.$refs.range.valueAsNumber)
        }, false)
        this.currentTimeSong = audio.currentTime
        // 绑定进度条
        this.currentTime = audio.currentTime / this.time * 100
        // 进度条运行中-定时器
        this.stop = setInterval(function () {
          if (_this.currentTime >= 99) {
            console.log('ok')
            clearInterval(_this.stop)
          } else {
            _this.currentTimeSong = audio.currentTime
            _this.currentTime = audio.currentTime / _this.time * 100
          }
        }, 500)
        // 进度条拖动和点击，这是进度条点击
        this.$refs.timeBar.addEventListener('mousedown', function (e) {
          console.log(1)
          _this.currentTimeSong = audio.currentTime
          _this.currentTime = e.offsetX / this.clientWidth * 100
          audio.currentTime = _this.currentTime * _this.time / 100
        }, false)
        // 进度条拖动和点击，当鼠标点击到进度按钮上
        this.$refs.timeThumb.addEventListener('mousedown', function (e) {
          e.stopPropagation()
          e.preventDefault()
          _this.currentTimeSong = audio.currentTime
          timeThumbIsDown = true
        }, false)
        // 进度条拖动和点击，鼠标释放
        document.addEventListener('mouseup', function (e) {
          _this.currentTimeSong = audio.currentTime
          timeThumbIsDown = false
        }, false)
        // 进度条拖动和点击，鼠标移动
        document.addEventListener('mousemove', function (e) {
          e.stopPropagation()
          if (timeThumbIsDown) {
            let pageX = e.screenX - _this.$refs.timeBar.offsetLeft
            if (pageX >= 0 && pageX <= _this.$refs.timeBar.clientWidth) {
              _this.currentTimeSong = audio.currentTime
              _this.currentTime = (e.screenX - _this.$refs.timeBar.offsetLeft) / _this.$refs.timeBar.clientWidth * 100
              audio.currentTime = _this.currentTime * _this.time / 100
            } else {
              return false
            }
          }
        }, false)
      },
      play () {
        !this.$refs.audio.paused ? this.$refs.audio.pause() : this.$refs.audio.play()
        this.isPaused = this.$refs.audio.paused
        console.log(this.isPaused)
      },
      getLrc (id) {
        // 歌词获取
        var _this = this
        this.$http.get('/lyric?id=' + id).then(function (response) {
          // console.log(response.data.lrc.lyric)
          // console.log('↑↑↑↑↑__歌词__↑↑↑↑↑')
          _this.songLrc = response.data.lrc.lyric.split('\n')
          for (let i in _this.songLrc) {
            _this.songLrcTime[i] = _this.songLrc[i].match(/\[(.+?)\]/g)
            if (_this.songLrcTime[i] !== null) {
              let mi = parseInt(_this.songLrcTime[i][0].replace('[', '').replace(']', '').split(':')[0]) * 60
              let sec = parseInt(_this.songLrcTime[i][0].replace('[', '').replace(']', '').split(':')[1])
              _this.songLrcTime[i] = mi + sec
            }
          }
        }).catch(function (error) {
          console.log(error)
        })
      },
      playlistShow () { // 歌单展开
        console.log('最近播放列表展开关闭')
        this.isPlaylistShow = !this.isPlaylistShow
      },
      playListClick (song, index) { // 点击歌单
        this.currentIndex = index
        this.current.id = song.id
        this.current.author = song.author
        this.current.pic = song.pic
        this.current.title = song.title
        this.current.url = song.url
        this.getLrc(song.id)
      },
      loopType () { // 循环设置
        if (this.loopTypeNumber === 1) {
          console.log('单曲循环')
          this.$refs.audio.play()
        } else if (this.loopTypeNumber === 2) {
          console.log('列表循环')
          this.currentIndex ++
          if (this.currentIndex === this.songList.length) {
            this.currentIndex = 0
          }
          this.changeSong()
        } else if (this.loopTypeNumber === 3) {
          console.log('随机播放')
          this.currentIndex = Math.floor(Math.random() * this.songList.length)
          this.changeSong()
        } else if (this.loopTypeNumber === 4) {
          console.log('顺序播放')
          this.currentIndex ++
          if (this.currentIndex === this.songList.length) {
            this.currentIndex = this.songList.length - 1
          }
          this.changeSong()
        } else {
          return
        }
      },
      nextSong () { // 下一首
        this.currentIndex ++
        if (this.currentIndex === this.songList.length) {
          this.currentIndex = 0
        }
        this.changeSong()
      },
      preSong () { // 上一首
        this.currentIndex --
        if (this.currentIndex === -1) {
          this.currentIndex = this.songList.length - 1
        }
        this.changeSong()
      },
      loopIcon () { // 循环切换
        this.loopTypeNumber ++
        if (this.loopTypeNumber === 5) {
          this.loopTypeNumber = 1
        }
        if (this.loopTypeNumber === 1) {
          this.classObject['icon-danquxunhuan'] = true
          this.classObject['icon-xunhuan'] = false
          this.classObject['icon-suijibofang'] = false
          this.classObject['icon-shunxubofang'] = false
          this.loopString = '单曲循环'
        } else if (this.loopTypeNumber === 2) {
          this.classObject['icon-danquxunhuan'] = false
          this.classObject['icon-xunhuan'] = true
          this.classObject['icon-suijibofang'] = false
          this.classObject['icon-shunxubofang'] = false
          this.loopString = '列表循环'
        } else if (this.loopTypeNumber === 3) {
          this.classObject['icon-danquxunhuan'] = false
          this.classObject['icon-xunhuan'] = false
          this.classObject['icon-suijibofang'] = true
          this.classObject['icon-shunxubofang'] = false
          this.loopString = '随机播放'
        } else if (this.loopTypeNumber === 4) {
          this.classObject['icon-danquxunhuan'] = false
          this.classObject['icon-xunhuan'] = false
          this.classObject['icon-suijibofang'] = false
          this.classObject['icon-shunxubofang'] = true
          this.loopString = '顺序播放'
        } else {
          return
        }
      },
      playlistDel (song, index) { // 删除歌单中的歌曲.
        if (this.songList.length === 1) {
          return
        }
        this.songList.splice(index, 1)
        // 删除之后，再存入缓存
        if (localStorage) {
          localStorage.setItem('cacheSongList', JSON.stringify(this.songList))
        }
      },
      setSong () { // 设置歌曲，在初始化中使用
        this.currentIndex = this.songList.length - 1
        this.changeSong()
      },
      changeSong () { // 设置歌曲，在切换中使用
        this.current.id = this.songList[this.currentIndex].id
        this.current.author = this.songList[this.currentIndex].author
        this.current.pic = this.songList[this.currentIndex].pic
        this.current.title = this.songList[this.currentIndex].title
        this.current.url = this.songList[this.currentIndex].url
        this.getLrc(this.songList[this.currentIndex].id)
      }
    },
    created () {
      // console.log('已挂载播放器')
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style>
  .playlistDel{
    position:absolute;
    right:0;
    cursor:pointer;
    font-size:16px;
  }
  .playlist{
    position:absolute;
    bottom:140px;
    width:50%;
    max-width:520px;
    overflow-x:hidden;
    overflow-y:auto;
    max-height:200px;
    z-index:9999;
    left:0;
    background:rgba(50,200,255,0.9);
    padding:20px;
    text-align: left;
    font-size:14px;
    line-height:25px;
    color:#333;
    box-shadow: 1px 1px 5px rgba(0,150,255,0.25);
    -webkit-box-shadow: 1px 1px 5px rgba(0,150,255,0.25);
  }
  .playlist h3{font-size:14px;margin:0 0 10px 30px;cursor:pointer;}
  .playlist li{
    position:relative;
    padding:0 10px 0 30px;
    overflow:hidden;
    height:25px;
  }
  .playlist li.on{
    background:url(../assets/sj.png) no-repeat scroll 0 50%;
    background-size:auto 100%;
  }
  .playlist dl{
    float:left;
  }
  dl,p,li{
    margin:0;
  }
  .audio{
    position:relative;
    height:120px;
    -webkit-box-shadow: 0 0 5px rgba(0,200,255,0.95);
    box-shadow: 0 0 5px rgba(0,200,255,0.95);
    background: rgba(0,200,255,0.10);
    color:#ccc;
  }
  .music-pic{
    float:left;
    width:120px;
    height:120px;
    position: relative;
  }
  .music-pic .iconfont{
    -webkit-transition:all 100ms linear;
    transition:all 100ms linear;
    opacity: 0.8;
    cursor: pointer;
  }
  .music-pic .iconfont:hover{
    opacity: 1;
  }
  .audio .icon-bofangqi3{
    position: absolute;
    width:40px;
    height:40px;
    line-height:40px;
    top:50%;
    left:50%;
    color:#fff;
    font-size:40px;
    margin:-18px 0 0 -20px;
  }
  .audio .icon-zanting{
    position: absolute;
    width:26px;
    height:26px;
    line-height:26px;
    top:70%;
    left:70%;
    color:#fff;
    font-size:26px;
  }
  .music-pic img{
    width:100%;
    height:100%;
  }
  .music-info{
    text-align: left;
    font-size:14px;
    height:20px;
  }
  .music-lrc{
    height:60px;
    margin:5px 0 8px;
    overflow: hidden;
    font-size: 12px;
    position: relative;
    text-align:center;
  }
  .music-lrc-box{
    width: 100%;
    -webkit-transition: all 0.5s ease-out;
    transition: all 0.5s ease-out;
    user-select: text;
    -webkit-user-select: text;
    position: absolute;
    top: 0;
    left: 0;
  }
  .music-lrc dl{
    line-height:20px;
  }
  .music-controls-box{
    margin:0 0 0 125px;
    padding:10px 7px 0 7px;
  }
  .music-controls{
    line-height:6px;
    height:6px;
  }
  .time-bar{
    height:6px;
    width:100%;
    position:relative;
    float:left;
  }
  .time-number{
    float:right;
    font-size:12px;
    margin-right:5px;
  }
  .time-bar,.time-loaded,.time-played{
    border-radius: 10px;
    -webkit-border-radius: 10px;
  }
  .song-btns{
    line-height:7px;
    float:left;
    padding-right: 5px;
  }
  .song-btns i{
    margin-right: 5px;
    cursor:pointer;
  }
  .song-bar-l{
    float:left;
  }
  .song-bar-r{
    margin-left:134px;
    margin-right:88px;
  }
  .song-volume,.song-loop,.song-menu{padding-right:10px;float:left;cursor:pointer;position:relative;}
  .song-menu{line-height:8px;padding-right:0;}
  .volume-controls{
    display:inline-block;
    position:absolute;
    top:-37px;
    left:-18px;
    transform: rotate(-90deg)
  }
  input[type=range] {
    -webkit-appearance: none;
    width: 50px;
    border-radius: 10px; /*这个属性设置使填充进度条时的图形为圆角*/
  }
  input[type=range]::-webkit-slider-thumb {
      -webkit-appearance: none;
  }
  input[type=range]::-moz-slider-thumb {
      -moz-appearance: none;
  }
  input[type=range]::-webkit-slider-runnable-track {
    height: 6px;
    border-radius: 10px; /*将轨道设为圆角的*/
    background:rgba(22,125,255,0.32);
  }
  input[type=range]::-moz-slider-runnable-track {
    height: 4px;
    border-radius: 10px; /*将轨道设为圆角的*/
    background:rgba(22,125,255,0.32);
  }
  input[type=range]:focus {
    outline: none;
  }
  input[type=range]::-webkit-slider-thumb {
    -webkit-appearance: none;
    height: 8px;
    width: 8px;
    margin-top:-1px;
    background: #17BAFF; 
    border-radius: 50%; /*外观设置为圆形*/
  }
  input[type=range]::-moz-slider-thumb {
    -moz-appearance: none;
    height: 8px;
    width: 8px;
    margin-top:-1px;
    background: #17BAFF; 
    border-radius: 50%; /*外观设置为圆形*/
  }
  .time-loaded{
    height:100%;
    width:100%;
    background:rgba(0,200,255,0.20);
    top:0;
    left:0;
    position:absolute;
  }
  .time-played{
    position:absolute;
    top:0;
    left:0;
    height:100%;
    width:50%;
    background:rgba(0,200,255,0.5);
  }
  .time-thumb{
    position:absolute;
    width:14px;
    height:14px;
    top:-4px;
    right:-10px;
    background:#17BAFF;
    border-radius:50%;
    -webkit-border-radius:50%;
    cursor:pointer;
  }
  .iconfont-box{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
  .iconfont-box.on{
    background: rgba(0,0,0,0.2);
  }
</style>
